package com.yanx.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 集合工具
 * 基于Hutool
 *
 * @author gotanks
 * @version 1.0
 * @since 2020-05-13
 */
public final class Collect_ extends CollUtil {

    /**
     * 将list转为其中一个字段的数组
     *
     * @param list
     * @param fieldName
     * @param <T>
     * @return
     */
    public static <T> Long[] list2LongArr(Collection<T> list, String fieldName) {
        String methodName = String_.upperFirstAndAddPre(fieldName, "get");
        return list.stream().map(t -> ReflectUtil.invoke(t, methodName)).toArray(Long[]::new);
    }

    /**
     * 对象去重
     *
     * @param list
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> List<T> distinct(List<T> list, Function<? super T, ?> keyExtractor) {
        return list.stream().filter(distinctByKey(keyExtractor)).collect(Collectors.toList());
    }

    /**
     * 对象去重辅助方法
     *
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}
